<template>
    <div class="product-category-management">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">
                    <i class="el-icon-menu"></i>
                    商品分类管理
                </h1>
                <p class="page-description">管理商品分类结构，支持多级分类管理</p>
            </div>
            <div class="header-actions">
                <el-button type="primary" @click="handleAdd" icon="el-icon-plus" class="add-btn" size="medium">
                    新增分类
                </el-button>
            </div>
        </div>

        <!-- 分类树展示区域 -->
        <el-card class="category-tree-card" shadow="hover">
            <div slot="header" class="card-header">
                <span class="card-title">
                    <i class="el-icon-s-grid"></i>
                    分类树结构
                </span>
                <el-tag type="info" size="small">
                    共 {{ getTotalCategories() }} 个分类
                </el-tag>
            </div>

            <div class="tree-container">
                <el-tree :data="categoryTree" :props="defaultProps" :expand-on-click-node="false"
                    :render-content="renderContent" @node-click="handleNodeClick" class="custom-tree" node-key="id">
                </el-tree>
            </div>
        </el-card>

        <!-- 添加/编辑分类对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" class="category-dialog"
            :close-on-click-modal="false">
            <el-form :model="categoryForm" :rules="categoryRules" ref="categoryForm" label-width="100px"
                class="category-form">

                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="categoryForm.name" placeholder="请输入分类名称" prefix-icon="el-icon-edit">
                    </el-input>
                </el-form-item>

                <el-form-item label="父分类" prop="parentId">
                    <el-select v-model="categoryForm.parentId" placeholder="请选择父分类" class="full-width">
                        <el-option value="0" label="无父分类（顶级分类）"></el-option>
                        <el-option v-for="category in allCategories" :key="category.id"
                            :label="getCategoryLabel(category)" :value="category.id"
                            v-if="category.level < 3 && (dialogType === 'add' || category.id !== categoryForm.id)">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="categoryForm.sort" :min="0" :max="100" label="排序值"
                        controls-position="right" class="full-width">
                    </el-input-number>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-switch v-model="categoryForm.status" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用">
                    </el-switch>
                </el-form-item>

                <el-form-item label="图标">
                    
                    
                    <!-- 图片上传组件 -->
                    <el-upload 
                        v-if="!categoryForm.icon" 
                        action="https://api.zctj16888.com/admin/v1/image/ossUpload"
                        list-type="picture-card" 
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove" 
                        :on-success="handleAvatarSuccess"
                        :on-error="handleUploadError"
                        name="image"
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        accept="image/*"
                        class="icon-upload">
                        <i class="el-icon-plus"></i>
                        <div class="upload-tip">点击上传图标</div>
                    </el-upload>
                    
                    <!-- 已上传图片预览 -->
                    <div v-else class="icon-preview-container">
                        <img :src="categoryForm.icon" alt="分类图标" class="preview-image">
                        <div class="icon-actions">
                            <el-button type="text" icon="el-icon-view" @click="previewIcon" size="small">预览</el-button>
                            <el-button type="text" icon="el-icon-delete" @click="deleteImg" size="small" class="delete-btn">删除</el-button>
                        </div>
                    </div>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="medium">取消</el-button>
                <el-button type="primary" @click="handleSubmit" size="medium" :loading="submitLoading">
                    确定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// 导入必要的API服务
// import {
//     getCategoryList,
//     addCategory,
//     updateCategory,
//     deleteCategory,
// } from '@/api/shopping/category';
import { categoryList, categorySave } from '../../../libs/api'
export default {
    name: 'ProductCategoryManagement',
    data() {
        return {
            categoryTree: [], // 分类树数据
            allCategories: [], // 所有分类列表（平级）
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            dialogVisible: false,
            dialogType: 'add', // 'add' 或 'edit'
            dialogTitle: '新增分类',
            submitLoading: false,
            categoryForm: {
                id: '',
                parentId: 0,
                name: '',
                sort: 50,
                status: 1,
                icon: '',
            },
            categoryRules: {
                name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 1, max: 50, message: '分类名称长度在1到50个字符之间', trigger: 'blur' },
                ],
                sort: [
                    { required: true, message: '请输入排序值', trigger: 'blur' },
                    { type: 'number', message: '排序值必须是数字', trigger: 'blur' },
                ],
            },
        };
    },
    created() {
        this.loadCategoryList();
    },
    methods: {
        deleteImg() {
            this.categoryForm.icon = ''
        },

        // 图片上传相关方法
        handleAvatarSuccess(response, file) {
            if (response.code === 1) {
                this.categoryForm.icon = response.data.url || response.data;
                this.$message.success('图片上传成功');
            } else {
                this.$message.error(response.message || '图片上传失败');
            }
        },

        handleRemove(file, fileList) {
            this.$message.success('图片已移除');
        },

        handlePictureCardPreview(file) {
            this.$alert(`<img src="${file.url}" style="width: 100%; max-width: 500px;">`, '图片预览', {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '关闭'
            });
        },

        // 上传前验证
        beforeUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('只能上传图片文件!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过 2MB!');
                return false;
            }
            return true;
        },

        // 上传错误处理
        handleUploadError(err, file) {
            console.error('上传失败:', err);
            this.$message.error('图片上传失败，请重试');
        },

        // 预览图标
        previewIcon() {
            if (this.categoryForm.icon) {
                this.$alert(`<img src="${this.categoryForm.icon}" style="width: 100%; max-width: 500px;">`, '图标预览', {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '关闭'
                });
            }
        },
        // 获取分类总数
        getTotalCategories() {
            return this.allCategories.length;
        },

        // 获取分类标签显示
        getCategoryLabel(category) {
            const levelPrefix = '　'.repeat(category.level - 1);
            return levelPrefix + category.name;
        },

        // 判断是否为图片URL
        isImageUrl(url) {
            return url && (url.startsWith('http') || url.startsWith('data:'));
        },

        // 加载分类列表
        async loadCategoryList() {
            const res = await categoryList()

            // 这里使用模拟数据，实际项目中应替换为API调用

            this.categoryTree = res.data;
            this.flattenCategories(res.data);

            // 实际项目中应使用以下API调用
            /*
            getCategoryList()
              .then((response) => {
                this.categoryTree = response.data;
                this.flattenCategories(response.data);
              })
              .catch((error) => {
                this.$message.error('获取分类列表失败');
                console.error(error);
              });
            */
        },

        // 将分类树展平为列表
        flattenCategories(categories) {
            this.allCategories = [];
            const flatten = (cats) => {
                cats.forEach((category) => {
                    this.allCategories.push({
                        id: category.id,
                        name: category.name,
                        level: category.level,
                        parent_id: category.parent_id,
                    });

                    if (category.children && category.children.length > 0) {
                        flatten(category.children);
                    }
                });
            };
            flatten(categories);
        },

        // 渲染分类节点内容
        renderContent(h, { node, data, store }) {
            return (
                <div class="custom-tree-node">
                    <div class="node-content" style="display:flex; align-items: center;">

                        { data.icon ?  <img style="width:25px;height:25px;" src={data.icon}  /> : '' }
                        
                       
                        <span class="node-label">{data.name}</span>
                        <div class="node-actions">
                            <el-button
                                size="mini"
                                type="primary"
                                icon="el-icon-edit"
                                class="action-btn edit-btn"
                                on-click={() => this.handleEdit(data)}>
                                编辑
                            </el-button>

                        </div>

                    </div>

                </div>
            );
        },

        // 节点点击事件
        handleNodeClick(data) {
            console.log('节点点击:', data);
        },

        // 处理新增分类
        handleAdd() {
            this.dialogType = 'add';
            this.dialogTitle = '新增分类';
            this.categoryForm = {
                id: '',
                parentId: 0,
                name: '',
                sort: 50,
                status: 1,
                icon: '',
            };
            this.dialogVisible = true;
        },

        // 处理编辑分类
        handleEdit(data) {
            this.dialogType = 'edit';
            this.dialogTitle = '编辑分类';
            this.categoryForm = {
                id: data.id,
                parentId: data.parent_id,
                name: data.name,
                sort: data.sort,
                status: data.status,
                icon: data.icon || '',
            };
            this.dialogVisible = true;
        },

        // 处理删除分类
        handleDelete(id) {
            this.$confirm('确定要删除该分类吗？删除后将无法恢复！', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    // 实际项目中应调用API删除分类
                    /*
                    deleteCategory(id)
                      .then(() => {
                        this.$message.success('删除成功');
                        this.loadCategoryList();
                      })
                      .catch((error) => {
                        this.$message.error('删除失败');
                        console.error(error);
                      });
                    */

                    // 模拟删除成功
                    this.$message.success('删除成功');
                    this.loadCategoryList();
                })
                .catch(() => {
                    this.$message.info('已取消删除');
                });
        },

        // 提交表单
        async handleSubmit() {
            this.$refs.categoryForm.validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true;

                    try {
                        // 准备提交的数据
                        const submitData = {
                            parent_id: this.categoryForm.parentId.toString(),
                            name: this.categoryForm.name,
                            sort: this.categoryForm.sort.toString(),
                            icon: this.categoryForm.icon || '',
                            status: this.categoryForm.status.toString(),
                        };

                        // 如果是编辑模式，需要添加ID
                        if (this.dialogType === 'edit') {
                            submitData.id = this.categoryForm.id.toString();
                        }

                        // 调用 categorySave 接口
                        const res = await categorySave(submitData);
                        // console.log(res)
                        if (res.code === 1) {
                            this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功');
                            this.dialogVisible = false;
                            this.loadCategoryList();
                        } else {
                            this.$message.error(res.message || (this.dialogType === 'add' ? '添加失败' : '更新失败'));
                        }
                    } catch (error) {
                        console.error('提交失败:', error);
                        this.$message.error(this.dialogType === 'add' ? '添加失败' : '更新失败');
                    } finally {
                        this.submitLoading = false;
                    }
                }
            });
        },
    },
};
</script>

<style scoped>
.product-category-management {
    min-height: 100vh;
    /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
    padding: 20px;
}

/* 页面标题区域 */
.page-header {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-content {
    flex: 1;
}

.page-title {
    margin: 0 0 8px 0;
    font-size: 28px;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-title i {
    color: #667eea;
    font-size: 32px;
}

.page-description {
    margin: 0;
    color: #7f8c8d;
    font-size: 16px;
}

.header-actions {
    flex-shrink: 0;
}

.add-btn {
    background: linear-gradient(45deg, #667eea, #764ba2);
    border: none;
    border-radius: 12px;
    padding: 12px 24px;
    font-weight: 500;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    transition: all 0.3s ease;
}

.add-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
}

/* 分类树卡片 */
.category-tree-card {
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: none;
    overflow: hidden;
}

.card-header {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    border-bottom: 1px solid #dee2e6;
    padding: 20px 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 8px;
}

.card-title i {
    color: #667eea;
}

.tree-container {
    padding: 24px;
    background: #fff;
}

/* 自定义树样式 */
.custom-tree {
    font-size: 14px;
}

.custom-tree .el-tree-node__content {
    height: auto;
    padding: 12px 0;
    border-radius: 8px;
    margin: 4px 0;
    transition: all 0.3s ease;
}

.custom-tree .el-tree-node__content:hover {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    transform: translateX(4px);
}

.custom-tree .el-tree-node__expand-icon {
    color: #667eea;
    font-size: 16px;
}

/* 自定义树节点 */
.custom-tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 8px 16px;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid #e9ecef;
    transition: all 0.3s ease;
}

.custom-tree-node:hover {
    background: rgba(255, 255, 255, 1);
    border-color: #667eea;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.node-content {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
}

.node-icon {
    width: 32px;
    height: 32px;
    border-radius: 6px;
    overflow: hidden;
    flex-shrink: 0;
}

.category-icon {
    width: 30px;
    height: 30px;
    object-fit: cover;
}

.node-label {
    font-weight: 500;
    color: #2c3e50;
    font-size: 15px;
}

.node-info {
    display: flex;
    gap: 8px;
    margin-left: 16px;
}

.node-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
}

.action-btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.edit-btn {
    background: linear-gradient(45deg, #3498db, #2980b9);
    border: none;
}

.edit-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}

.delete-btn {
    //background: linear-gradient(45deg, #e74c3c, #c0392b);
    border: none;
}

.delete-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
}

/* 对话框样式 */
.category-dialog .el-dialog {
    border-radius: 16px;
    overflow: hidden;
}

.category-dialog .el-dialog__header {
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    padding: 20px 24px;
}

.category-dialog .el-dialog__title {
    color: white;
    font-weight: 600;
}

.category-dialog .el-dialog__body {
    padding: 30px 24px;
}

.category-form .el-form-item {
    margin-bottom: 24px;
}

.category-form .el-input,
.category-form .el-select,
.category-form .el-input-number {
    border-radius: 8px;
}

.category-form .el-input__inner,
.category-form .el-select .el-input__inner {
    border-radius: 8px;
    border: 2px solid #e9ecef;
    transition: all 0.3s ease;
}

.category-form .el-input__inner:focus,
.category-form .el-select .el-input__inner:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.full-width {
    width: 100%;
}

.icon-preview {
    margin-top: 8px;
    text-align: center;
}

.preview-image {
    width: 40px;
    height: 40px;
    border-radius: 6px;
    object-fit: cover;
    border: 2px solid #e9ecef;
}

.preview-icon {
    font-size: 32px;
    color: #667eea;
    display: block;
    margin: 4px 0;
}

/* 图标上传组件样式 */
.icon-upload {
    margin-top: 12px;
}

.icon-upload .el-upload--picture-card {
    width: 146px;
    height: 146px;
    line-height: 146px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}

.icon-upload .el-upload--picture-card:hover {
    border-color: #667eea;
    background-color: #f8f9fa;
}

.icon-upload .el-icon-plus {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 8px;
}

.upload-tip {
    font-size: 12px;
    color: #8c939d;
    line-height: 1.2;
}

.icon-preview-container {
    margin-top: 12px;
    text-align: center;
}

.icon-preview-container .preview-image {
    width: 146px;
    height: 146px;
    border-radius: 8px;
    object-fit: cover;
    border: 2px solid #e9ecef;
    margin-bottom: 8px;
}

.icon-actions {
    display: flex;
    justify-content: center;
    gap: 8px;
}

.icon-actions .el-button {
    padding: 4px 8px;
    font-size: 12px;
}

.icon-actions .delete-btn {
    color: #f56c6c;
}

.icon-actions .delete-btn:hover {
    color: #f78989;
}

.dialog-footer {
    text-align: right;
    padding: 20px 24px;
    background: #f8f9fa;
    border-top: 1px solid #dee2e6;
}

.dialog-footer .el-button {
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .product-category-management {
        padding: 16px;
    }

    .page-header {
        flex-direction: column;
        gap: 20px;
        text-align: center;
    }

    .page-title {
        font-size: 24px;
    }

    .custom-tree-node {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .node-actions {
        width: 100%;
        justify-content: flex-end;
    }
}

/* 动画效果 */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.category-tree-card {
    animation: fadeInUp 0.6s ease-out;
}

.custom-tree-node {
    animation: fadeInUp 0.4s ease-out;
}
</style>